import { LOGIN_FAIL, LOGIN_START, LOGIN_SUCCESS } from "../actions/user";
import { produce } from "immer";
import store2 from "store2"; //封装过的本地操作方法库
let initState = {
  isLoading: false, //控制登录的loading状态
  isLogin: false, //判断登录状态
  userInfo: null, //存放用户信息
};
//尝试提取本地存储用户信息
let info = store2.get("react-admin-2301");
if (info) {
  initState.isLogin = true;
  initState.userInfo = info;
}
export const user = (state = initState, action) => {
  switch (action.type) {
    case LOGIN_START:
      return produce(state, (draft) => {
        draft.isLoading = true;
      });
    case LOGIN_SUCCESS:
      return produce(state, (draft) => {
        draft.isLoading = false;
        draft.isLogin = true;
        draft.userInfo = action.userInfo;
        store2.set("react-admin-2301", action.userInfo); //本地存储（也可以使用原生js）
      });
    case LOGIN_FAIL: //登录失败、退出登录
      return produce(state, (draft) => {
        draft.isLoading = false;
        draft.isLogin = false;
        draft.userInfo = null;
        store2.remove("react-admin-2301");
      });

    default:
      return state;
  }
};
